'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { 
  IconClock, 
  IconUsers, 
  IconAlertTriangle, 
  IconActivity,
  IconMoon,
  IconSun,
  IconSunset,
  IconMoonStars,
  IconPlayerPlay,
  IconPlayerPause
} from '@tabler/icons-react'
import { demoController, demoScenarios, type DemoScenario } from '@/lib/demoScenarios'

interface ScenarioSelectorProps {
  onScenarioChange?: (data: any) => void
  className?: string
}

const getTimeIcon = (timeOfDay: string) => {
  switch (timeOfDay) {
    case 'morning': return <IconSun className="w-4 h-4" />
    case 'afternoon': return <IconSunset className="w-4 h-4" />
    case 'evening': return <IconMoon className="w-4 h-4" />
    case 'night': return <IconMoonStars className="w-4 h-4" />
    default: return <IconClock className="w-4 h-4" />
  }
}

const getTimeLabel = (timeOfDay: string) => {
  switch (timeOfDay) {
    case 'morning': return '上午'
    case 'afternoon': return '下午'
    case 'evening': return '晚间'
    case 'night': return '深夜'
    default: return '未知'
  }
}

const getSeverityColor = (scenario: DemoScenario) => {
  const { patientFlowMultiplier, alertSeverityIncrease } = scenario.dataModifiers
  
  if (patientFlowMultiplier > 1.5 || alertSeverityIncrease) {
    return 'destructive'
  } else if (patientFlowMultiplier > 1.2) {
    return 'warning'
  } else {
    return 'secondary'
  }
}

export function ScenarioSelector({ onScenarioChange, className }: ScenarioSelectorProps) {
  const [currentScenario, setCurrentScenario] = useState<string>('afternoon_normal')
  const [isAutoMode, setIsAutoMode] = useState(false)
  const [autoInterval, setAutoInterval] = useState<NodeJS.Timeout | null>(null)

  // 手动切换场景
  const handleScenarioChange = (scenarioId: string) => {
    setCurrentScenario(scenarioId)
    demoController.setScenario(scenarioId)
    const data = demoController.getData()
    onScenarioChange?.(data)
  }

  // 开启/关闭自动演示
  const toggleAutoMode = () => {
    if (isAutoMode) {
      // 停止自动模式
      if (autoInterval) {
        clearInterval(autoInterval)
        setAutoInterval(null)
      }
      setIsAutoMode(false)
    } else {
      // 开启自动模式
      setIsAutoMode(true)
      const cleanup = demoController.startAutoDemo((data) => {
        setCurrentScenario(demoController.currentScenario)
        onScenarioChange?.(data)
      }, 45000) // 45秒切换一次场景
      
      // 保存清理函数
      const intervalId = setTimeout(() => {}, 0) // 占位符
      setAutoInterval(intervalId)
      
      // 替换为实际的清理函数
      setTimeout(() => {
        setAutoInterval(cleanup as any)
      }, 0)
    }
  }

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (autoInterval) {
        clearInterval(autoInterval)
      }
    }
  }, [autoInterval])

  const currentScenarioData = demoScenarios.find(s => s.id === currentScenario)

  return (
    <Card className={className}>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg">演示场景控制</CardTitle>
          <Button
            variant={isAutoMode ? "destructive" : "default"}
            size="sm"
            onClick={toggleAutoMode}
            className="flex items-center gap-2"
          >
            {isAutoMode ? (
              <>
                <IconPlayerPause className="w-4 h-4" />
                停止自动
              </>
            ) : (
              <>
                <IconPlayerPlay className="w-4 h-4" />
                自动演示
              </>
            )}
          </Button>
        </div>
      </CardHeader>
      
      <CardContent className="space-y-4">
        {/* 场景选择器 */}
        <div className="space-y-2">
          <label className="text-sm font-medium">选择场景</label>
          <Select 
            value={currentScenario} 
            onValueChange={handleScenarioChange}
            disabled={isAutoMode}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {demoScenarios.map((scenario) => (
                <SelectItem key={scenario.id} value={scenario.id}>
                  <div className="flex items-center gap-2">
                    {getTimeIcon(scenario.timeOfDay)}
                    <span>{scenario.name}</span>
                    {scenario.isWeekend && (
                      <Badge variant="outline" className="text-xs">周末</Badge>
                    )}
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        {/* 当前场景信息 */}
        {currentScenarioData && (
          <div className="space-y-3 p-3 bg-muted/30 rounded-lg">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                {getTimeIcon(currentScenarioData.timeOfDay)}
                <span className="font-medium">{currentScenarioData.name}</span>
                <Badge variant={getSeverityColor(currentScenarioData)}>
                  {getTimeLabel(currentScenarioData.timeOfDay)}
                </Badge>
              </div>
              {isAutoMode && (
                <Badge variant="outline" className="animate-pulse">
                  自动中
                </Badge>
              )}
            </div>
            
            <p className="text-sm text-muted-foreground">
              {currentScenarioData.description}
            </p>

            {/* 场景特征 */}
            <div className="grid grid-cols-2 gap-2 text-xs">
              <div className="flex items-center gap-1">
                <IconUsers className="w-3 h-3" />
                <span>患者流量: {Math.round(currentScenarioData.dataModifiers.patientFlowMultiplier * 100)}%</span>
              </div>
              
              {currentScenarioData.dataModifiers.alertSeverityIncrease && (
                <div className="flex items-center gap-1 text-orange-600">
                  <IconAlertTriangle className="w-3 h-3" />
                  <span>告警增加</span>
                </div>
              )}
              
              {currentScenarioData.dataModifiers.equipmentIssues && (
                <div className="flex items-center gap-1 text-blue-600">
                  <IconActivity className="w-3 h-3" />
                  <span>设备维护</span>
                </div>
              )}
              
              {currentScenarioData.dataModifiers.crowdingAreas.length > 0 && (
                <div className="col-span-2">
                  <span className="text-red-600">拥挤区域: </span>
                  <span>{currentScenarioData.dataModifiers.crowdingAreas.join('、')}</span>
                </div>
              )}
            </div>

            {/* 特殊事件 */}
            {currentScenarioData.specialEvents && currentScenarioData.specialEvents.length > 0 && (
              <div className="space-y-1">
                <span className="text-sm font-medium">特殊事件:</span>
                <div className="flex flex-wrap gap-1">
                  {currentScenarioData.specialEvents.map((event, index) => (
                    <Badge key={index} variant="outline" className="text-xs">
                      {event}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* 快速场景按钮 */}
        <div className="space-y-2">
          <label className="text-sm font-medium">快速切换</label>
          <div className="grid grid-cols-2 gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleScenarioChange('morning_rush')}
              disabled={isAutoMode}
              className="justify-start"
            >
              <IconSun className="w-4 h-4 mr-2" />
              早高峰
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleScenarioChange('evening_emergency')}
              disabled={isAutoMode}
              className="justify-start"
            >
              <IconMoon className="w-4 h-4 mr-2" />
              晚间急诊
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleScenarioChange('flu_season')}
              disabled={isAutoMode}
              className="justify-start"
            >
              <IconAlertTriangle className="w-4 h-4 mr-2" />
              流感季
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleScenarioChange('night_quiet')}
              disabled={isAutoMode}
              className="justify-start"
            >
              <IconMoonStars className="w-4 h-4 mr-2" />
              深夜值班
            </Button>
          </div>
        </div>

        {/* 状态提示 */}
        <div className="text-xs text-muted-foreground text-center pt-2 border-t">
          {isAutoMode 
            ? '自动演示模式：每45秒切换一次场景'
            : '手动模式：选择场景查看不同时段的医院运营数据'
          }
        </div>
      </CardContent>
    </Card>
  )
}

export default ScenarioSelector